<template>
  <div>
    <a-popover v-model="visible" title="" placement="bottomRight" trigger="click">

      <template v-if="visible" slot="content">
        <div id="tableSettings" :style="passStyle">
          <div class="tableSettingBottomBtn anclear">
            <span class="fl">展示列设置</span>
            <a-button type="link" size="small" @click="resetF()">重置</a-button>
          </div>
          <a-divider style="margin:10px 0 20px 0" />

          <p>固定到左侧</p>
          <a-checkbox-group
            v-model="checkedValueLeft"
            @change="fixedLeftChange"
          >
            <div v-for="item in fixedLeft" :key="'left'+item.value+(new Date - 0)" class="anclear" style="text-align: left;">
              <a-col :span="14">
                <a-tooltip placement="left">
                  <template slot="title">
                    <span>取消展示</span>
                  </template>
                  <a-checkbox :value="item.value" :disabled="item.disabled">{{ item.label }}</a-checkbox>
                </a-tooltip>

              </a-col>
              <a-col :span="10">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    取消固定到左侧
                  </template>
                  <a-button class="icon-lefts" size="small" :style="{color:item.fixed==='left'?'blue':'#ddd'}" type="link" @click="fixedF('left',item.value)">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>

                <a-divider type="vertical" />
                <a-tooltip placement="right">
                  <template slot="title">
                    <span v-if="rightEnough">右侧已满</span>
                    <span v-else>固定到右侧</span>
                  </template>
                  <a-button
                    class="icon-rights"
                    size="small"
                    :disabled="rightEnough"
                    :style="{color:item.fixed==='right'?'blue':'#ddd'}"
                    type="link"
                    @click="fixedF('right',item.value)">
                    <a-icon type="pushpin" />
                  </a-button>

                </a-tooltip>

              </a-col>
            </div>

          </a-checkbox-group>
          <p>固定到右侧</p>
          <a-checkbox-group
            v-model="checkedValueRight"
            @change="fixedRightChange"
          >
            <div v-for="item in fixedRight" :key="'right'+item.value+(new Date - 0)" class="anclear" style="text-align: left;">
              <a-col :span="14">
                <a-tooltip placement="left">
                  <template slot="title">
                    <span>取消展示</span>
                  </template>
                  <a-checkbox :value="item.value" :disabled="item.disabled">{{ item.label }}</a-checkbox>
                </a-tooltip>

              </a-col>
              <a-col :span="10">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span v-if="leftEnough">左侧已满</span>
                    <span v-else>固定到左侧</span>
                  </template>
                  <a-button
                    class="icon-lefts"
                    size="small"
                    :disabled="leftEnough"
                    :style="{color:item.fixed==='left'?'blue':'#ddd'}"
                    type="link"
                    @click="fixedF('left',item.value)">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
                <a-divider type="vertical" />
                <a-tooltip placement="right">
                  <template slot="title">
                    取消固定到右侧
                  </template>
                  <a-button class="icon-rights" size="small" :style="{color:item.fixed==='right'?'blue':'#ddd'}" type="link" @click="fixedF('right',item.value)">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
              </a-col>
            </div>

          </a-checkbox-group>
          <a-divider style="margin:10px 0 20px 0" />
          <a-checkbox-group
            v-model="checkedValueNotFixed"
            class="notFixed"
            @change="notFixedChange"
          >
            <div v-for="item in notFixed" :key="'middle'+item.value+(new Date - 0)" class="anclear" style="text-align: left;">
              <a-col :span="14">
                <a-tooltip placement="left">
                  <template slot="title">
                    <span v-if="item.hasChildren">复杂表头</span>
                    <span v-else-if="checkedValueNotFixed.includes(item.value)">取消展示</span>
                    <span v-else>选中展示</span>
                  </template>
                  <a-checkbox :value="item.value" :disabled="item.disabled">{{ item.label }}</a-checkbox>
                </a-tooltip>
              </a-col>
              <a-col :span="10">
                <a-tooltip v-if="item.parent.includes(',')" placement="topLeft">
                  <template slot="title">
                    <span>复杂表头</span>
                  </template>
                  <a-button
                    class="icon-lefts"
                    size="small"
                    :disabled="true"
                    :style="{color:'#ddd'}"
                    type="link">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
                <a-tooltip v-else placement="topLeft">
                  <template slot="title">
                    <span v-if="leftEnough">左侧已满</span>
                    <span v-else-if="item.hasChildren">复杂表头</span>
                    <span v-else> 固定到左侧</span>
                  </template>
                  <a-button
                    class="icon-lefts"
                    size="small"
                    :disabled="leftEnough||item.hasChildren"
                    :style="{color:item.fixed==='left'?'blue':'#ddd'}"
                    type="link"
                    @click="fixedF('left',item.value,0)">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
                <a-divider type="vertical" />
                <a-tooltip v-if="item.parent.includes(',')" placement="right">
                  <template slot="title">
                    <span>复杂表头</span>
                  </template>
                  <a-button
                    class="icon-rights"
                    size="small"
                    :disabled="true"
                    :style="{color:'#ddd'}"
                    type="link">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
                <a-tooltip v-else placement="right">
                  <template slot="title">
                    <span v-if="rightEnough">右侧已满</span>
                    <span v-else-if="item.hasChildren">复杂表头</span>
                    <span v-else> 固定到右侧</span>
                  </template>
                  <a-button
                    class="icon-rights"
                    size="small"
                    :disabled="rightEnough||item.hasChildren"
                    :style="{color:item.fixed==='right'?'blue':'#ddd'}"
                    type="link"
                    @click="fixedF('right',item.value,0)">
                    <a-icon type="pushpin" />
                  </a-button>
                </a-tooltip>
              </a-col>
            </div>

          </a-checkbox-group>
        </div>

      </template>
      <template v-else slot="content"></template>
      <a style="dispaly:inline-block" :size="buttonSize">
        <slot> <a-icon type="setting" /></slot>
      </a>
    </a-popover>

  </div>
</template>
<script>
// import { deepCopy } from '@/utils/util.js'

export default {
  name: 'TableSettings',
  props: {
    passStyle: {
      type: Object,
      default: () => {
        return {
          width: '220px'
        }
      }
    },
    tableTheadCopy: {
      type: Array,
      default: () => []
    },
    tableThead: {
      type: Array,
      default: () => []
    },
    buttonSize: {
      type: String,
      default: 'small'
    },
    tableScroll: {
      type: Object,
      default: () => {
        return { x: 1500, y: 400 }
      }
    },
    tableTdWidth: {
      type: Number,
      default: 50
    }
  },
  data () {
    return {
      visible: false,
      fixedLeft: [],
      checkedValueLeft: [],
      fixedRight: [],
      checkedValueRight: [],
      tableHeadCopyData: [],
      notFixed: [],
      checkedValueNotFixed: []
    }
  },
  computed: {
    leftEnough: function () {
      return this.fixedLeft.length >= 3
    },
    rightEnough: function () {
      return this.fixedRight.length >= 2
    }
  },
  watch: {
    'visible': {
      handler (newValue) {
        if (newValue) {
          this.fixedLeft = []
          this.checkedValueLeft = []
          this.fixedRight = []
          this.checkedValueRight = []
          this.tableHeadCopyData = []
          this.notFixed = []
          this.checkedValueNotFixed = []
          console.log(JSON.parse(JSON.stringify(this.tableThead)))
          this.reset(this.tableThead)
        }
      }
    }
  },
  created () {
    setTimeout(() => {
      this.fixedLeft = []
      this.checkedValueLeft = []
      this.fixedRight = []
      this.checkedValueRight = []
      this.tableHeadCopyData = []
      this.notFixed = []
      this.checkedValueNotFixed = []
      console.log(JSON.parse(JSON.stringify(this.tableThead)))
      this.reset(this.tableThead)
    }, 100000)
    
  },
  methods: {
    resetF () {
      Object.assign(this.$data, this.$options.data.call(this))
      this.reset(this.tableTheadCopy)
    },
    digui (arrays, parent) {
      const finallyData = []

      arrays.forEach(item => {
        if (item.children && item.children.length > 0) {
          this.digui(item.children, item.key)
        } else {
          if ([null, undefined].includes(item.fixed)) {
            this.checkedValueNotFixed = this.checkedValueNotFixed.concat(item.key)
          }
          let canshu = {
            mySort: item.mySort,
            sorter: item.sorter,
            defaultSortOrder: item.defaultSortOrder,
            awaysShow: item.awaysShow,
            dataIndex: item.dataIndex,
            hidden: item.hidden || false,
            label: item.title,
            value: item.key,
            fixed: item.fixed,
            disabled: item.awaysShow || Boolean(item.children && item.children.length),
            hasChildren: Boolean(item.children && item.children.length),
            parent: item.key
          }

          if(item.scopedSlots){
            canshu.scopedSlots = item.scopedSlots
          }
          if(item.width){
            canshu.width = item.width
          }
          finallyData.push(canshu)
        }
      })
      return finallyData
    },
    reset (newValue) {
      const tableHeadCopyData = []

      newValue.forEach((item, index) => {
        let canshu = {
          mySort: item.mySort || index,
          sorter: item.sorter,
          defaultSortOrder: item.defaultSortOrder,
          awaysShow: item.awaysShow,
          dataIndex: item.dataIndex,
          hidden: item.hidden || false,
          label: item.title,
          value: item.key,
          fixed: item.fixed,
          disabled: item.awaysShow || Boolean(item.children && item.children.length),
          hasChildren: Boolean(item.children && item.children.length),
          parent: item.key
        }

        if(item.scopedSlots){
          canshu.scopedSlots = item.scopedSlots
        }
        if(item.width){
          canshu.width = item.width
        }
        // 回头考虑复杂表头

        if (item.children && item.children.length > 0) {
          tableHeadCopyData.push(canshu)
          tableHeadCopyData.push(this.digui(item.children, item.key))
        } else {
          tableHeadCopyData.push(canshu)
        }
      })
      console.log(JSON.parse(JSON.stringify(tableHeadCopyData)))
      this.tableHeadCopyData = this.tableHeadCopyData.concat(tableHeadCopyData)

      this.getFixedLeftRight()
    },
    // type==1点击的是固定的 type===0点击的是最下边非固定的
    fixedF (position, value, type = 1) {
      if (type === 0) {
        this.checkedValueNotFixed = this.checkedValueNotFixed.filter(item => item !== value)
      }
      this.tableHeadCopyData.forEach((item, index) => {
        if (item.value === value) {
          // 单纯取消固定 取消后应该照常显示
          item.hidden = false
          if (item.fixed === position) {
            item.fixed = null
            this.checkedValueNotFixed.push(item.value)
          } else {
            item.fixed = position
          }
        }
      })
      this.getFixedLeftRight()
    },
    getFixedLeftRight () {
      const checkedValueNotFixed = []

      const fixedLeft = []; const fixedRight = []; const checkedValueLeft = []
      const checkedValueRight = []; const notFixed = []

      console.log(JSON.parse(JSON.stringify(this.tableHeadCopyData)))
      this.tableHeadCopyData.forEach(item => {
        // 只要固定了就一定显示 在固定时候取消了选中会将fixed变为null
        if (item.fixed === 'left') {
          fixedLeft.push(item)
          checkedValueLeft.push(item.value)
        } else if (item.fixed === 'right') {
          fixedRight.push(item)
          checkedValueRight.push(String(item.value))
        } else {
          notFixed.push(item)
          if (!item.hidden) {
            checkedValueNotFixed.push(item.value)
          }
        }
      })
      this.notFixed = notFixed
      this.fixedLeft = fixedLeft
      this.fixedRight = fixedRight
      this.checkedValueNotFixed = checkedValueNotFixed
      this.checkedValueLeft = checkedValueLeft
      this.checkedValueRight = checkedValueRight
      // console.log(JSON.parse(JSON.stringify(this.checkedValueNotFixed)))
      this.computedScrollAndNewColumns(this.tableHeadCopyData)
    },
    /// 待开发 适配多表头的情况
    diguie (arrays) {
      arrays.forEach(item => {
        if (item.children && item.children.length > 0) {
          this.diguie(item.children)
        } else if (this.checkedValueNotFixed.includes(item.key) ||
                        this.checkedValueLeft.includes(item.key) ||
                        this.checkedValueRight.includes(item.key)) {
          item.hidden = false
        } else {
          item.hidden = true
        }
      })
    },
    fixedLeftChange (checkedValue) {
      this.clearSelectLEFTRIGHT(checkedValue, 'fixedLeft')
    },
    // 取消左固定又固定的checkbox选中状态
    clearSelectLEFTRIGHT (checkedValue, arrayName) {
      const currentEdditCheckBoxData = this[arrayName].filter(item => {
        if (!checkedValue.includes(item.value)) {
          return true
        }
      })[0]

      console.log(currentEdditCheckBoxData)
      this.tableHeadCopyData.forEach(item => {
        if (item.value === currentEdditCheckBoxData.value) {
          item.fixed = null
          item.hidden = true
        }
      })
      this.getFixedLeftRight()
    },
    fixedRightChange (checkedValue) {
      this.clearSelectLEFTRIGHT(checkedValue, 'fixedRight')
    },
    notFixedChange (checkedValue) {
      console.log(JSON.parse(JSON.stringify(this.tableHeadCopyData)))
      this.tableHeadCopyData.forEach(item => {
        if (this.checkedValueNotFixed.includes(item.value) ||
                    this.checkedValueLeft.includes(item.value) ||
                this.checkedValueRight.includes(item.value)) {
          item.hidden = false
        } else {
          item.hidden = true
          item.fixed = ''
        }
      })

      this.computedScrollAndNewColumns(this.tableHeadCopyData)
    },
    computedScrollAndNewColumns (showThad) {
      const scroll = {
        x: 0,
        y: this.tableScroll.y
      }
      const trWidth = 15
      const left = []
      const middle = []
      const right = []

      showThad.forEach((item, index) => {
        if (item.fixed === 'left') {
          left.push(item)
        } else if (item.fixed === 'right') {
          right.push(item)
        } else {
          middle.push(item)
        }
        // if (!item.hidden) {
        //   item.width = 100
        //   if (item.children && item.children.length > 0) {
        //     item.children.forEach(item2 => {
        //       if (!item2.hidden) {
        //         item2.width = item2.width || this.tableTdWidth
        //       }
        //     })
        //   }
        // }
      })
      function sortArray (arrays) {
        return arrays.sort((a, b) => {
          return a.mySort - b.mySort
        })
      }
      const linshi = [...sortArray(left), ...sortArray(middle), ...sortArray(right)]

      scroll.x = trWidth
      // this.$emit('update:tableScroll', scroll)
      const tableTHEADE = []

      linshi.forEach(item => {
        let canshu = {
          mySort: item.mySort,
          sorter: item.sorter,
          defaultSortOrder: item.defaultSortOrder,
          title: item.label,
          width: item.width,
          dataIndex: item.dataIndex,
          key: item.value,
          awaysShow: item.awaysShow,
          hidden: item.hidden,
          fixed: item.fixed
        }

        if(item.scopedSlots){
          canshu.scopedSlots = item.scopedSlots
        }
        if(item.width){
          canshu.width = item.width
        }
        tableTHEADE.push(canshu)
      })
      this.$emit('update:tableThead', tableTHEADE)
    }
  }
}
</script>

<style lang="scss">
#tableSettings{
  .ant-checkbox-group.notFixed{
    max-height: 300px;
    overflow: auto;
  }
  .ant-divider, .ant-divider-vertical{
    margin:0 1px;
  }
}
#tableSettings .ant-checkbox-group{
  width:100%;
}
  .icon-lefts{
    transform: rotate(90deg);
    &:hover{
      i{
        color:blue
      }
    }
  }
  .icon-rights{
    transform: rotate(180deg);
    &:hover{
      i{
        color:blue
      }
    }
  }
  .tableSettingBottomBtn{
    text-align: center;
	margin-bottom: 10px;
	&>span{
		color:#000;
		font-weight: 700;
	}
  }
</style>
